package com.asialjim.wechat.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;

/**
 * <h1><em>ASIAL JIM JAVA DOC</em></h1><hr/>
 * <h2>CLASS DESCRIPTION <i>[ NAME: XmlUtils ]</i></h2><strong>
 * <p> xml utils
 * </strong><p><p><em>Copyright &copy; Asial Jim Co., LTD</em><hr/>
 *
 * @author Asial Jim &nbsp;&nbsp; <span>Email:<a href="mailto:asialjim@hotmail.com">asialjim@hotmail.com</a> &nbsp;&nbsp; <a href="asialjim@qq.com">asialjim@qq.com</a></span>
 * @version 1.0.0
 * @since 2021/1/26   &nbsp;&nbsp; JDK 8
 */
@Slf4j
public class XmlUtils {
    private static final XmlMapper XML_MAPPER = new XmlMapper();

    static {
        // 转成对象时，可以忽略多余参数
        XML_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        XML_MAPPER.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
        //mapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
        //mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    }
    /**
     * <h3>METHOD DESCRIPTION <i>[ NAME: xml2Object ]</i></h3>
     * parse xml 2 object
     * @param xml {@link String xml}
     * @param type {@link Class targetObjectClass}
     * @param <T> target object class
     * @return {@link T targetObject}
     * @author Asial Jim &nbsp;&nbsp;<span>Email:asialjim@hotmail.com &nbsp;&nbsp; asialjim@qq.com</span>
     * @since 2021/1/27 10:10
     */
    public static<T> T xml2Object(String xml, Class<T> type){
        try {
            return XML_MAPPER.readValue(xml,type);
        } catch (IOException e) {
            log.info("xml 对象装欢异常："+e.getMessage());
            throw new RuntimeException("xml对象转换异常"+e.getMessage());
        }
    }

    /**
     * <h3>METHOD DESCRIPTION <i>[ NAME: object2Xml ]</i></h3>
     * parse object 2 xml
     * @param object {@link Object sourceObject}
     * @return {@link String target xml}
     * @author Asial Jim &nbsp;&nbsp;<span>Email:asialjim@hotmail.com &nbsp;&nbsp; asialjim@qq.com</span>
     * @since 2021/1/27 10:11
     */
    public static String object2Xml(Object object){
        try {
            return XML_MAPPER.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            log.info("{}转换为xml异常：{}",object.getClass(),e.getMessage());
            throw new RuntimeException("对象："+object.getClass()+"转换为xml异常"+e.getMessage());
        }
    }
}